package heapSort;

public class Buid {
	public int arr[];
	public Buid(int[] a){
		arr = a;
	}
	
	public String toString(){
		StringBuilder result = new StringBuilder();
		for (int i =0; i<arr.length; i++){
			result.append(arr[i]);
			result.append(" ");
		}
		return "Arr is " + result;
		
	}

	public void buidHeap(){
		for(int i = arr.length/2; i>0; i--){
			adjust(i, arr.length);
		
		}
		
		for (int j = arr.length-1; j>0; j--){
			int temp;
			temp = arr[0];
			arr[0] = arr[j];
			arr[j] = temp;
			adjust(1, j);
			
		}
			
	}
	
	public void adjust(int s, int limit){
		int change;
		
		for (int i = s; i <arr.length && 2*i <arr.length; i = change+1){
			change = 2*i-1;
			if (arr[change] > arr[2*i])
				change += 1;
			if (arr[i-1] > arr[change] && change < limit){
			int temp = arr[i-1];
			arr[i-1] = arr[change];
			arr[change] = temp;
			}
		}
	}
	
	public static void main(String args[]){
		int testArr[] = {55, 38, 27, 49, 76, 65, 49, 97};
		Buid test = new Buid(testArr);
		test.buidHeap();
		System.out.println(test);
		
		
	}
}

